package com.ruoyi.kenuo.utils;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
@Slf4j
public class MqttConfig {

    @Value("${spring.mqtt.host-url}")
    private String hostUrl;

    @Value("${spring.mqtt.client-id}")
    private String clientId;

    @Value("${spring.mqtt.username}")
    private String username;

    @Value("${spring.mqtt.password}")
    private String password;

    @Value("${spring.mqtt.connection-timeout}")
    private int connectionTimeout;

    @Value("${spring.mqtt.keep-alive-interval}")
    private int keepAliveInterval;

    @Value("${spring.mqtt.default-topics}")
    private String[] defaultTopics;

    @Value("${spring.mqtt.qos}")
    private int qos;



    // 核心：配置遗嘱消息
    String willTopic = "client/status/" + clientId; // 遗嘱主题（包含客户端ID，便于识别）
    String willPayload = "{\"clientId\":\"" + clientId + "\",\"status\":\"offline\"}"; // 遗嘱内容（离线状态）

    /**
     * 创建MQTT客户端连接
     */
    @Bean
    public MqttClient mqttClient() throws MqttException {
        // 内存持久化（也可使用文件持久化）
        MemoryPersistence persistence = new MemoryPersistence();
        MqttClient client = new MqttClient(hostUrl, clientId, persistence);

        // 设置连接参数
        MqttConnectOptions options = new MqttConnectOptions();
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(connectionTimeout);
        options.setKeepAliveInterval(keepAliveInterval);
        options.setAutomaticReconnect(true); // 自动重连
        options.setCleanSession(false); // 不清除会话（保留订阅关系）
        options.setWill(willTopic, willPayload.getBytes(), 1, false); // QoS 1，不保留消息
        // 设置回调处理类
        client.setCallback(new MqttCallbackExtended() {
            @Override
            public void connectComplete(boolean reconnect, String serverURI) {
                if (reconnect) {
                    System.out.println("客户端重连成功，服务器地址：" + serverURI);
                    // 重连后发布“在线”状态（与遗嘱消息的“离线”对应）
                    try {
                        String onlinePayload = "{\"clientId\":\"" + clientId + "\",\"status\":\"online\"}";
                        client.publish(willTopic, onlinePayload.getBytes(), 1, false);
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("客户端首次连接成功");
                }
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                log.info("收到MQTT消息 - 主题: {}, 内容: {}, QoS: {}",
                        topic,
                        new String(message.getPayload()),
                        message.getQos());
                // 处理消息
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {

                try {
                    log.info("消息发送完成 - 主题: {}", token.getTopics()[0]);
                } catch (Exception e) {
                    log.error("消息发送回调异常", e);
                }

            }

            @Override
            public void connectionLost(Throwable cause) {
                System.out.println("客户端连接丢失：" + cause.getMessage());
            }
        });

        // 连接服务器并订阅默认主题
        if (!client.isConnected()) {
            client.connect(options);
            client.subscribe(defaultTopics, new int[]{qos, qos}); // 为每个主题设置QoS
            // 首次连接成功后发布“在线”状态
            String onlinePayload = "{\"clientId\":\"" + clientId + "\",\"status\":\"online\"}";
            client.publish(willTopic, onlinePayload.getBytes(), 1, false);
        }
        return client;
    }



}
